<template>
  <a-modal
    title="请选择登录机构"
    v-model:visible="openModal"
    :mask-closable="false"
    unmount-on-close
    :closable="false"
    title-align="start"
    width="800px"
  >
    <a-table
      :loading="loading"
      :columns="columns"
      :data="sysList"
      :row-selection="rowSelection"
      v-model:selected-keys="ids"
      row-key="deptId"
      :pagination="{
        total: total,
        current: queryParams.pageNum,
        pageSize: queryParams.pageSize
      }"
      @page-change="tablePageChange"
      @row-click="
        (row) => {
          ids = [row.deptId]
        }
      "
    >
      <template #createTime="{ record }">
        <span>{{ record.createTime }}</span>
      </template>
    </a-table>
    <template #footer>
      <a-row justify="center">
        <a-button
          type="primary"
          @click="intoSystem"
          :loading="okLoading"
          :disabled="ids.length !== 1"
          class="login-btn"
          >进入系统</a-button
        >
      </a-row>
    </template>
  </a-modal>
</template>

<script setup name="LoginOrgSelect">
import { tempTokenGetDeptList } from '@/api/login'
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  tempToken: {
    type: String,
    default: ''
  }
})

const rowSelection = reactive({
  type: 'radio'
})

const openModal = computed(() => {
  return props.open
})

const loading = ref(false)
const okLoading = ref(false)
const ids = ref([])

const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 5
})

const emits = defineEmits(['intoSystem', 'update:open'])

const columns = ref([
  {
    title: '机构名称',
    dataIndex: 'deptName'
  },
  {
    title: '开通日期',
    slotName: 'createTime'
  },
  {
    title: '管理员姓名',
    dataIndex: 'realName'
  }
])
const sysList = ref([])

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      ids.value = []
      handleQuery()
    }
  }
)

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function getList() {
  loading.value = true
  tempTokenGetDeptList({
    ...queryParams.value,
    tempToken: props.tempToken
  }).then((response) => {
    sysList.value = response.rows.map((i) => {
      return {
        deptId: i.deptId,
        deptName: i.deptName,
        createTime: i.createTime,
        realName: i.realName
      }
    })
    total.value = response.total
    loading.value = false
  })
}

// 分页变化
function tablePageChange(pageNum) {
  queryParams.value.pageNum = pageNum
  getList()
}

function intoSystem() {
  emits('intoSystem', ids.value[0])
  emits('update:open', false)
}
</script>

<style lang="scss" scoped>
.login-btn {
  // background-color: $--color-primary !important;
  // color: #fff;
}
</style>
